package com.scwatch.core.html;

import com.scwatch.common.file.FileHandler;
import com.scwatch.common.freemarker.Freemarkers;
import com.scwatch.common.util.Dates;
import com.scwatch.common.web.PathResolver;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.service.TaskService;
import com.scwatch.core.support.Context;
import com.scwatch.core.support.ForeContext;
import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.io.IOException;
import java.util.*;

/**
 * PNode
 * 
 * @author gjl
 * 
 */
public abstract class PNode {
	public static void makeHtml(Node node, int max, Configuration config, PathResolver pathResolver,
			TaskService taskService, Integer taskId,Map<String,Object> dataMap) throws IOException, TemplateException {
		if (node == null) {
			return;
		}
		deleteHtml(node, pathResolver);
		node.updateHtmlStatus();
		if (!node.getGenerate()) {
			return;
		}
		Context.setMobile(false);
		try {
			doMakeHtml(node, max, config, pathResolver, taskService, taskId,dataMap);
			// 生成手机端HTML
			if (node.getSite().getMobilePublishPoint() != null
					&& node.getSite().getMobilePublishPoint().getId() != node.getSite().getHtmlPublishPoint().getId()
					&& StringUtils.isNotBlank(node.getSite().getMobileDomain())) {
				Context.setMobile(true);
				doMakeHtml(node, max, config, pathResolver, taskService, taskId,dataMap);
			}
		} finally {
			Context.resetMobile();
		}
	}

	public static void doMakeHtml(Node node, int max, Configuration config, PathResolver pathResolver,
			TaskService taskService, Integer taskId,Map<String,Object> dataMap) throws IOException, TemplateException {
		Site site = node.getSite();
		System.out.println("---------PNode make------------:"+node.getName()+"nodeId:"+node.getId());
		Template template = config.getTemplate(node.getTemplate());
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put(FreemarkerServlet.KEY_APPLICATION, Collections.EMPTY_MAP);
		rootMap.put(FreemarkerServlet.KEY_SESSION, Collections.EMPTY_MAP);
		rootMap.put(FreemarkerServlet.KEY_REQUEST, Collections.EMPTY_MAP);
		rootMap.put(Freemarkers.KEY_PARAMETERS, Collections.EMPTY_MAP);
		rootMap.put(Freemarkers.KEY_PARAMETER_VALUES, Collections.EMPTY_MAP);
		rootMap.put("node", node);
		if(node!=null && node.getTreeLevel().intValue()==0){
		    List<Node> indexNodes=new ArrayList<>();
		    for(Node n:node.getChildren()){
               if(n.getPublish()!=null && "0".equals(n.getPublish())){
                  indexNodes.add(n);
               }
            }
           rootMap.put("indexNodes",indexNodes);
        }
		Integer total = 1;
        int subTotal=1;
        int liveTotal=1;
        int backTotal=1;

		int staticPage = node.getStaticPageOrDef();
		PublishPoint publishPoint = Context.isMobile() ? node.getSite().getMobilePublishPoint() : node.getSite()
				.getHtmlPublishPoint();
		FileHandler fileHandler = publishPoint.getFileHandler(pathResolver);
		for (int page = 0; page < max && page < total && page < staticPage && taskService.isRunning(taskId); page++) {
			String filename = node.getUrlStatic(page, false, true, Context.isMobile());
			if (page == 0) {
				if (Context.isMobile()) {
					node.getDetail().setMobileHtml(filename);
				} else {
					node.getDetail().setHtml(filename);
				}
				if (max >= staticPage || max >= total) {
					node.setHtmlStatus(Node.HTML_GENERATED);
				} else {
					node.setHtmlStatus(Node.HTML_TOBE_UPDATE);
				}
			}
			// TODO like info:InfoText,title,text.
			rootMap.put("text", node.getText());
			String url = node.getUrlStatic(page);
			ForeContext.setData(rootMap, site, null, null, null, null, null, null, url);
			ForeContext.setPage(rootMap, page, node);
            //1. 回看
            String tp1=node.getSite().getTemplate("/json/proback_infos.ftl");
            Template  prolistTemp=config.getTemplate(tp1);
            String lookBackSharedTp=node.getSite().getTemplate("/h5/look_back_shared.html");
            Template  lookBackSharedTemp=config.getTemplate(lookBackSharedTp);
            List<Programback> programbacks=dataMap==null?null:(List<Programback>)dataMap.get("programbacks");
            if(node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
                    && (Constants.MODEL_TV_of_yesterday.equals(node.getNodeModel().getFlag())
                    || Constants.MODEL_FLAG_SCTV.equals(node.getNodeModel().getFlag()))){
                if(programbacks!=null && programbacks.size()>0){
                    for(Programback proBack:programbacks){
                        if(proBack!=null && proBack.getProgramDatecheacks()!=null && proBack.getProgramDatecheacks().size()>0){
                            int num=0;
                            for(ProgramDatecheack proDate:proBack.getProgramDatecheacks()){
                                if(num>=7){
                                    break;
                                }
                                if(StringUtils.isBlank(proDate.getName()) || proDate.getProgramBackcodes()==null || proDate.getProgramBackcodes().size()==0){
                                    continue;
                                }
                                //回看节目单文件名
                                String str1=node.getDomainPath();
//                            String str1=url.replaceFirst("/","");
//                            str1="/"+str1.substring(0,str1.indexOf("/"));
                                String fileStr=filename.substring(0,filename.lastIndexOf("/index"));
                                fileStr=fileStr +"/"+proBack.getId();
                                //路径进行时间判断,大于分割日期，按照年月日路径生成
                                Date divisionDate= Dates.formatDateStr(Constants.DIVISIONDATE,"yyyy-MM-dd HH:mm:ss");
                                if(proDate.getTime()!=null &&  proDate.getTime().compareTo(divisionDate)>0){
                                    fileStr=fileStr+"/{year}/{month}/{day}";
//                                    Calendar now = Calendar.getInstance();
//                                    now.setTime(proDate.getTime());
                                    String[] times = proDate.getName().split("-");
                                    String year = times[0];
                                    int m = Integer.valueOf(times[1]);
                                    int d = Integer.valueOf(times[2]);
                                    String month = StringUtils.leftPad(String.valueOf(m), 2, '0');
                                    String day = StringUtils.leftPad(String.valueOf(d), 2, '0');
                                    fileStr = StringUtils.replace(fileStr, "{year}", year);
                                    fileStr = StringUtils.replace(fileStr, "{month}", month);
                                    fileStr = StringUtils.replace(fileStr, "{day}", day);
                                }

                                fileStr=fileStr+"/"+proDate.getName().replaceAll("-","")+".json";
                                if(proBack.url==null){  //最新一期节目单url
                                    proBack.url=str1+fileStr;
                                }
                                //回看分享页
                                String lookbackSharedUrl=str1+fileStr;
                                lookbackSharedUrl=lookbackSharedUrl.replace(".json","_shared.html");
                                rootMap.put("proBack",proBack);
                                rootMap.put("programBackcodes",proDate.getProgramBackcodes());
                                rootMap.put("lookbackSharedUrl",lookbackSharedUrl);

                                fileHandler.storeFile(lookBackSharedTemp, rootMap, fileStr.replace(".json","_shared.html"));
                                fileHandler.storeFile(prolistTemp, rootMap, fileStr);

                                proDate.setProgramBackcodes(null);
                                num++;
                            }

                        }
                    }
                }
                rootMap.put("programbacks",programbacks);
                if(Constants.MODEL_FLAG_SCTV.equals(node.getNodeModel().getFlag())){
                    String tp2=node.getSite().getTemplate("/json/lookback_infos.ftl");
                    Template  backlistTemp=config.getTemplate(tp2);
                    String str1=node.getDomainPath();
//                    String str1=url.replaceFirst("/","");
//                    str1="/"+str1.substring(0,str1.indexOf("/"));
                    String fileStr=filename.substring(0,filename.lastIndexOf("/"))+"/"+"lookback.json";
                    List<Sinatv> sinatvList=dataMap==null?null:(List<Sinatv>)dataMap.get("sinatvList");

                    //节目单内容，单独生成json
                    String tp3=node.getSite().getTemplate("/json/programs.ftl");
                    Template programsTemp=config.getTemplate(tp3);
                    String proPrefixUrl=filename.substring(0,filename.lastIndexOf("/"))+"/";
                    List<Sinatv> tvList=new ArrayList<>();
                    List<Sinatv> audioList=new ArrayList<>();
                    for(Sinatv tv:sinatvList){
                        if("1".equals(tv.getTvType())){  //视频
                            String proUrl=proPrefixUrl+tv.getId()+".json";
                            rootMap.put("programmesJson",tv.getProgrammes());
                            tv.setProgrammesJsonUrl(str1+proUrl);
                            fileHandler.storeFile(programsTemp, rootMap, proUrl);
                            tvList.add(tv);
                        }else{  //音频
                            audioList.add(tv);
                        }
                    }
                    fileHandler.storeFile(backlistTemp, rootMap, fileStr);
                    rootMap.put("tvList",tvList);
                    rootMap.put("audioList",audioList);
                    rootMap.put("newDate",Dates.formatDate(new Date(),"yyyy-MM-dd"));
                    rootMap.put("backUrl",str1+fileStr);
                }

            }

            //3. 时讯、24小时要闻
            List<String> infoDates=dataMap==null?null:(List<String>)dataMap.get("infoDates");
            String queryDate=dataMap==null?null:(String)dataMap.get("queryDate");
            List<String> isStick=dataMap==null?null:(List<String>)dataMap.get("isStick");

            //时讯、24小时 按日期生成文件
            if(infoDates!=null && infoDates.size()>0 && node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
             &&(Constants.MODEL_FLAG_CURRENTNEWS.equals(node.getNodeModel().getFlag())
                    || Constants.MODEL_FLAG_24HOURSNEWS.equals(node.getNodeModel().getFlag()))){
                String tp2=node.getSite().getTemplate("/json/currentnews_list.ftl");
                if(Constants.MODEL_FLAG_24HOURSNEWS.equals(node.getNodeModel().getFlag())){
                    tp2=node.getSite().getTemplate("/json/24hour_list.ftl");
                }
                Template  currentTemp=config.getTemplate(tp2);

                Template  currentStick=config.getTemplate(node.getSite().getTemplate("/json/24hour_infos_stick.ftl"));

                String newcurrentFileName=filename.substring(0,filename.lastIndexOf("/"));
                if(page==0){
                    if(queryDate!=null){
                        newcurrentFileName=newcurrentFileName+"/"+queryDate.replaceAll("-","")+"/" +queryDate.replaceAll("-","")+".json";
                    }else{
                        newcurrentFileName=newcurrentFileName+"/"+infoDates.get(0).replaceAll("-","")+"/"
                                +infoDates.get(0).replaceAll("-","")+".json";
                    }

                }else{
                    if(queryDate!=null){
                        newcurrentFileName=newcurrentFileName+"/"+queryDate.replaceAll("-","")+"/" +queryDate.replaceAll("-","")+"_"+page+".json";
                    }else{
                        newcurrentFileName=newcurrentFileName+"/"+infoDates.get(0).replaceAll("-","")+"/"
                                +infoDates.get(0).replaceAll("-","")+"_"+page+".json";
                    }

                }
                Map<String, String> currDateMap = new TreeMap<String, String>(new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        // 降序排列
                        return o2.compareTo(o1);
                    }
                });
                for(String infodate:infoDates){
                    String currentFileName=filename.substring(0,filename.lastIndexOf("/"));
                    currentFileName=currentFileName+"/"+
                            infodate.replaceAll("-","")+"/"
                            +infodate.replaceAll("-","");
                    if(page==0){
                        currentFileName=currentFileName+".json";
                    }else{
                        currentFileName=currentFileName+"_"+page+".json";
                    }

                    String str1=url.replaceFirst("/","");
                    str1="/"+str1.substring(0,str1.indexOf("/"));
                    currDateMap.put(infodate,str1+currentFileName);
                }
                if(isStick!=null && isStick.size()>0){ //是否有置顶文件
                    String str1=url.replaceFirst("/","");
                    str1="/"+str1.substring(0,str1.indexOf("/"));
                    currDateMap.put("2088-01-01",str1+"/hour/stick.json");
                }
                if(queryDate!=null){
                    rootMap.put("startTime",Dates.formatDateStr(queryDate+" 00:00:00",null));
                    rootMap.put("endTime",Dates.formatDateStr(queryDate+" 23:59:59",null));
                }else{
                    rootMap.put("startTime",Dates.formatDateStr(infoDates.get(0)+" 00:00:00",null));
                    rootMap.put("endTime",Dates.formatDateStr(infoDates.get(0)+" 23:59:59",null));
                }
                rootMap.put("currDateMap",currDateMap);
                if(page==0){
                    fileHandler.storeFile(currentTemp,rootMap,filename);
                }
                fileHandler.storeFile(currentStick, rootMap, "/hour/stick.json");
                fileHandler.storeFile(template, rootMap, newcurrentFileName);
                taskService.add(taskId, 1);
                total = ForeContext.getTotalPages();
                if (total == null || total < 1) {
                    total = 1;
                }


            }else if(node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
                    &&(Constants.MODEL_FLAG_CITY_STATE.equals(node.getNodeModel().getFlag()))){
                String tp3=node.getSite().getTemplate("/json/citylist.ftl");
                Template  cityTemp=config.getTemplate(tp3);

                String str1=url.replaceFirst("/","");
                str1="/"+str1.substring(0,str1.indexOf("/"));
                String  cityFileName=filename.substring(0,filename.lastIndexOf("/"));
                if(page>0){
                    cityFileName=cityFileName+"/citydynamic_"+page+".json";
                }else{
                    cityFileName=cityFileName+"/citydynamic.json";
                }
                rootMap.put("institutionDynamicList",str1+cityFileName);

                if(page==0){
                    fileHandler.storeFile(cityTemp,rootMap,filename);
                }

                fileHandler.storeFile(template, rootMap, cityFileName);
                taskService.add(taskId, 1);
                total = ForeContext.getTotalPages();
                if (total == null || total < 1) {
                    total = 1;
                }


            }else if(node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
                    &&(Constants.MODEL_FLAG_HOTVIDEO.equals(node.getNodeModel().getFlag()))){
                String tp3=node.getSite().getTemplate("/json/video_infos.ftl");
                Template  videoTemp=config.getTemplate(tp3);


                String videoName=filename.substring(0,filename.lastIndexOf("/"))+"/video";
                if(page==0){
                    videoName=videoName+".json";
                    filename=filename.replaceFirst("video.json","morevideo.json");
                    url=url.replaceFirst("video.json","morevideo.json");
                }else{
                    filename=filename.replaceFirst("video_","morevideo_");
                    url=url.replaceFirst("video_","morevideo_");
                }
                rootMap.put("moreVideoUrl",url);
                if(page==0){
                    fileHandler.storeFile(videoTemp, rootMap, videoName);
                }

                fileHandler.storeFile(template, rootMap, filename);
                taskService.add(taskId, 1);
                total = ForeContext.getTotalPages();
                if (total == null || total < 1) {
                    total = 1;
                }
            }else if(node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
                    &&(Constants.MODEL_FLAG_LIVE_NODE.equals(node.getNodeModel().getFlag()))){
                String subTp=node.getSite().getTemplate("/json/livesub_list.ftl");
                String backTp=node.getSite().getTemplate("/json/liveback_list.ftl");
                String liveTp=node.getSite().getTemplate("/json/live_list.ftl");
                Template  subTemp=config.getTemplate(subTp);
                Template  backTemp=config.getTemplate(backTp);
                Template  liveTemp=config.getTemplate(liveTp);
                String subFileName=filename.substring(0,filename.lastIndexOf("/"))+"/livesub";
                String backFileName=filename.substring(0,filename.lastIndexOf("/"))+"/liveback";
                String liveFileName=filename.substring(0,filename.lastIndexOf("/"))+"/liveing";
                String str1=url.replaceFirst("/","");
                str1="/"+str1.substring(0,str1.indexOf("/"));
                if(page>0){
                    subFileName=subFileName+"_"+page+".json";
                    backFileName=backFileName+"_"+page+".json";
                    liveFileName=liveFileName+"_"+page+".json";
                }else{
                    subFileName=subFileName+".json";
                    backFileName=backFileName+".json";
                    liveFileName=liveFileName+".json";

                    rootMap.put("subUrl",str1+subFileName);
                    rootMap.put("backUrl",str1+backFileName);
                    rootMap.put("liveUrl",str1+liveFileName);
                    fileHandler.storeFile(template, rootMap,filename);
                }
                if(page<subTotal){
                    fileHandler.storeFile(subTemp, rootMap, subFileName);
                    subTotal=ForeContext.getTotalPages();
                }
                if(page<liveTotal){
                    fileHandler.storeFile(liveTemp, rootMap, liveFileName);
                    liveTotal=ForeContext.getTotalPages();
                }
                if(page<backTotal){
                    fileHandler.storeFile(backTemp, rootMap, backFileName);
                    backTotal=ForeContext.getTotalPages();
                }

                total=subTotal;
                if(liveTotal>total){
                   total=liveTotal;
                }
                if(backTotal>total){
                   total=backTotal;
                }
                taskService.add(taskId, 1);
                if (total == null || total < 1) {
                    total = 1;
                }

            }
//            else if(node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
//                    &&(Constants.MODEL_FLAG_LIVE.equals(node.getNodeModel().getFlag()))){
//
//
//
//            }
            else if(node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
                    &&(Constants.MODEL_FLAG_CITY_DETAIL.equals(node.getNodeModel().getFlag()))){
                //市州详情 以及市州分享页面
                String cityDetailTp=node.getSite().getTemplate("/h5/city_state_shared.html");
                Template  cityDetailTemp=config.getTemplate(cityDetailTp);
                String str1=node.getDomainPath();
                String cityDetailSharedUrl=str1+filename;
                if(page==0){
                    cityDetailSharedUrl=cityDetailSharedUrl.replace(".json","_shared.html");
                }else{
                    cityDetailSharedUrl=cityDetailSharedUrl.replace("_"+page+".json","_shared.html");
                }

                rootMap.put("cityDetailSharedUrl",cityDetailSharedUrl);
                if(page==0){
                  fileHandler.storeFile(cityDetailTemp, rootMap,filename.replace(".json","_shared.html"));
                }
                fileHandler.storeFile(template, rootMap, filename);
                taskService.add(taskId, 1);
                total = ForeContext.getTotalPages();
                if (total == null || total < 1) {
                    total = 1;
                }

            } else if(node.getNodeModel()!=null && node.getNodeModel().getFlag()!=null
                    &&(Constants.MODEL_FLAG_GC.equals(node.getNodeModel().getFlag()))){
                filename = "/gaoceng/index/"+node.getNumber()+".json";
                //高层新闻
                String userNews=node.getSite().getTemplate("/json/gaoceng_info.ftl");
                Template  userNewsTemp=config.getTemplate(userNews);
                rootMap.put("images",node.getDetail().getSmallImage());
                rootMap.put("userList",dataMap.get("userList"));
                List<GaoCeng> userList = (List<GaoCeng>) dataMap.get("userList");
                fileHandler.storeFile(template, rootMap, filename);
                for(GaoCeng gaoCeng : userList){
                 /*   Page<Info> infos = gaoCeng.getPageNewsList();
                    if(infos.getTotalPages()>1){
                        String tempFileName = "/gaoceng/gaoceng_info_"+gaoCeng.getId();
                        Pageable info = null;
                        for(int num=0;num<infos.getTotalPages();num++){
                            if(num>0){
                                info = infos.nextPageable();
                                rootMap.put("pagedList",infos.nextPageable());
                                tempFileName+="_"+num+ ".json";
                            }else{
                                rootMap.put("pagedList",gaoCeng.getPageNewsList());
                            }
                            fileHandler.storeFile(userNewsTemp, rootMap, tempFileName+".json");
                        }

                    }else {
                        rootMap.put("pagedList",gaoCeng.getPageNewsList());
                        fileHandler.storeFile(userNewsTemp, rootMap, "/gaoceng/gaoceng_info_"+gaoCeng.getId()+".json");
                    }*/
                    rootMap.put("newsList",gaoCeng.getPageNewsList().getContent());
                    fileHandler.storeFile(userNewsTemp, rootMap, "/gaoceng/gaoceng_info_"+gaoCeng.getId()+".json");
                }
            }else{
                fileHandler.storeFile(template, rootMap, filename);
                taskService.add(taskId, 1);
                total = ForeContext.getTotalPages();
                if (total == null || total < 1) {
                    total = 1;
                }
            }



		}
        dataMap=null;
	}

	public static void deleteHtml(Node node, PathResolver pathResolver) {
//		String html = node.getHtml();
//		FileHandler fileHandler = node.getSite().getHtmlPublishPoint().getFileHandler(pathResolver);
//		PNode.deleteHtml(html, fileHandler);
//		if (node.getDetail() != null) {
//			node.getDetail().setHtml(null);
//		}
//
//		String mobileHtml = node.getMobileHtml();
//		fileHandler = node.getSite().getMobilePublishPoint().getFileHandler(pathResolver);
//		PNode.deleteHtml(mobileHtml, fileHandler);
//		if (node.getDetail() != null) {
//			node.getDetail().setMobileHtml(null);
//		}
	}

	public static void deleteHtml(String html, FileHandler fileHandler) {
//		if (StringUtils.isBlank(html)) {
//			return;
//		}
//		String fullPath = FilenameUtils.getFullPath(html);
//		String baseName = FilenameUtils.getBaseName(html);
//		String extension = FilenameUtils.getExtension(html);
//		int page = 1;
//		while (StringUtils.isNotBlank(html)) {
//            String h5Url=html.replaceFirst(".json","_shared.html");
//            String sharedUrl=html.replaceFirst(".json","_h5.html");
//            fileHandler.delete(h5Url);
//            fileHandler.delete(sharedUrl);
//			boolean success = fileHandler.delete(html);
//			if (success) {
//				// 删除成功，继续删除
//				html = fullPath + baseName + "_" + page++ + "." + extension;
//
//
//			} else {
//				html = null;
//			}
//		}

	}
}
